#include<iostream>
//--------C---------
#include<cstdio>
#include<cstring>
#include<cerrno>
#include<cstdlib>
//-------system------
#include<sys/ipc.h>
#include<sys/shm.h>

#define FTOK_PATH "."
#define FTOK_PROJ_ID 0

#define DYNAMICS_SIZE 4096 

using namespace std;
key_t KeyCreate(){ 
    key_t key = ftok(FTOK_PATH,FTOK_PROJ_ID);
    if(key == -1){
        cerr<< "ftok():" << strerror(errno) << endl; 
        exit(-1);
    }
    return key;
}
int ShmCreateServer(){
    int shmid = shmget(KeyCreate(),DYNAMICS_SIZE,IPC_CREAT | IPC_EXCL | 0600);
    if(shmid == -1){
        cerr<< "ShmCreateServer -> shmget():" << strerror(errno) << endl; 
        return -1;
    }
    return shmid;
}
int ShmCreateClient(){
    int shmid = shmget(KeyCreate(),DYNAMICS_SIZE,IPC_CREAT);
    if(shmid == -1){
        cerr<< "ShmCreateClient -> shmget():" << strerror(errno) << endl; 
        exit(-1);
    }
    return shmid;
}

void* ShmAttach(int shmid){
    void* shmpoint = shmat(shmid,nullptr,0);
    if((long long)shmpoint == -1LL){
        cerr<< "shmAttach -> shmat()" << strerror(errno) << endl;
        exit(-1);
    }
    return shmpoint;
}  
void ShmDetach(void* shmpoint){
    int n = shmdt(shmpoint);
    if(n == -1){
        cerr<< "shmDetach -> shmdt()" << strerror(errno) << endl;
        exit(-1);
    }
    return;
}

void ShmDelete(int shmid){
    int n = shmctl(shmid,IPC_RMID,nullptr);
    if(n == -1){
        cerr << "ShmCreate -> shmctl():" << strerror(errno) << endl;
    }
    return;
}